<template>
  <div>
    <!-- 头部：姓名 + 置顶 + 元信息 -->
    <div class="d-flex align-center mb-1">
      <span class="text-subtitle-2 font-weight-medium">{{ note.user_name || '未知用户' }}</span>

      <v-icon class="mx-1" :icon="mdiCircleSmall" size="14" />
      <span class="text-caption text-medium-emphasis d-inline-flex align-center">
        <v-icon class="mr-1" :icon="mdiClockOutline" size="14" />
        {{ formatDateTime(note.created_at) }}
        <span v-if="note.updated_at !== note.created_at" class="ml-1">({{ t('edited') }})</span>
      </span>
    </div>

    <!-- 内容（解析特殊标记并渲染为可点击 Chip） -->
    <NoteContentRenderer
      class="note-content mb-1"
      :content="note.content"
      @click-company="handleClickCompany"
      @click-contact="handleClickContact"
      @click-user="handleClickUser"
    />

    <!-- 图片预览（支持大图，点击查看原图） -->
    <div v-if="note.images && note.images.length > 0" class="mb-2">
      <div class="d-flex flex-wrap ga-2">
        <v-img
          v-for="(img, i) in note.images"
          :key="i"
          :alt="img.alt || 'image'"
          class="note-image"
          cover
          :src="img.url"
          :style="{ width: `${imageSize}px`, height: `${imageSize}px`, flex: `0 0 ${imageSize}px` }"
          @click="openImage(img.url)"
        />
      </div>
    </div>

    <!-- 大图预览对话框 -->
    <v-dialog v-model="imagePreviewOpen" max-width="90vw">
      <v-card class="pa-2" rounded="lg">
        <v-img
          v-if="imagePreviewUrl"
          class="bg-grey-lighten-2"
          contain
          max-height="80vh"
          :src="imagePreviewUrl"
        />
      </v-card>
    </v-dialog>

    <!-- 关联信息（支持多公司/多联系人） -->
    <div v-if="companyList.length > 0 || contactList.length > 0" class="mb-1">
      <v-chip
        v-for="(name, i) in companyList"
        :key="'co-' + i"
        class="mr-1 mb-1"
        color="primary"
        size="x-small"
        variant="tonal"
      >
        <v-icon :icon="mdiDomain" size="small" start /> {{ name }}
      </v-chip>
      <v-chip
        v-for="(name, i) in contactList"
        :key="'ct-' + i"
        class="mr-1 mb-1"
        color="secondary"
        size="x-small"
        variant="tonal"
      >
        <v-icon :icon="mdiAccountBox" size="small" start /> {{ name }}
      </v-chip>
    </div>

    <!-- 附件 -->
    <div v-if="note.attachments && note.attachments.length > 0" class="mb-1">
      <v-chip
        v-for="(attachment, index) in note.attachments"
        :key="index"
        class="mr-2 mb-1"
        color="info"
        size="small"
        variant="outlined"
      >
        <v-icon :icon="mdiPaperclip" size="small" start /> {{ attachment }}
      </v-chip>
    </div>

    <!-- 操作菜单 -->
    <v-menu v-model="showMenu" :close-on-content-click="true" location="bottom end">
      <template #activator="{ props: p }">
        <v-btn
          v-bind="p"
          class="menu-btn"
          color="rgba(var(--v-theme-on-surface),1)"
          :icon="mdiDotsHorizontal"
          size="small"
          variant="text"
        />
      </template>

      <v-list density="compact">
        <v-list-item :prepend-icon="mdiPencil" @click="handleEdit">
          <v-list-item-title>{{ t('edit') }}</v-list-item-title>
        </v-list-item>

        <v-divider />

        <v-list-item :prepend-icon="mdiDelete" @click="handleDelete">
          <v-list-item-title class="text-error">{{ t('delete') }}</v-list-item-title>
        </v-list-item>
      </v-list>
    </v-menu>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import {
  mdiAccountBox,
  mdiCircleSmall,
  mdiClockOutline,
  mdiDelete,
  mdiDomain,
  mdiDotsHorizontal,
  mdiPaperclip,
  mdiPencil
} from '@mdi/js'
import type { Note } from '../../types'
import NoteContentRenderer from '../common/NoteContentRenderer.vue'

const props = defineProps<{ note: Note }>()
const { t } = useI18n()

const emit = defineEmits<{
  edit: [note: Note]
  delete: [noteId: number]
}>()

// 缩略图边长（px）
const imageSize = 120

const showMenu = ref(false)

// 图片预览状态
const imagePreviewOpen = ref(false)
const imagePreviewUrl = ref<string | null>(null)
function openImage(url: string) {
  imagePreviewUrl.value = url
  imagePreviewOpen.value = true
}

// 处理编辑
function handleEdit() {
  emit('edit', props.note)
  showMenu.value = false
}

// 处理删除
async function handleDelete() {
  if (confirm(t('confirmDelete'))) {
    emit('delete', props.note.id)
  }
  showMenu.value = false
}

// 关联实体列表（支持多个公司/联系人）
const companyList = computed<string[]>(() => {
  const n: any = props.note
  if (Array.isArray(n.companies))
    return n.companies
      .map((c: any) => (typeof c === 'string' ? c : (c?.name ?? '')))
      .filter(Boolean)
  if (Array.isArray(n.company_names)) return n.company_names.filter(Boolean)
  if (n.company_name) return [n.company_name]
  return []
})

const contactList = computed<string[]>(() => {
  const n: any = props.note
  if (Array.isArray(n.contacts))
    return n.contacts.map((c: any) => (typeof c === 'string' ? c : (c?.name ?? ''))).filter(Boolean)
  if (Array.isArray(n.contact_names)) return n.contact_names.filter(Boolean)
  if (n.contact_name) return [n.contact_name]
  return []
})

// 点击 chips 事件（可由上层接管导航）
function handleClickUser(p: { id: number; name: string }) {
  console.debug('[NoteContent] click-user', p)
}
function handleClickContact(p: { contactId: number; companyId: number; name: string }) {
  console.debug('[NoteContent] click-contact', p)
}
function handleClickCompany(p: { id: number; name: string }) {
  console.debug('[NoteContent] click-company', p)
}

// 格式化日期时间
function formatDateTime(timestamp: number): string {
  const date = new Date(timestamp)
  return date.toLocaleString()
}
</script>

<style scoped>
/* 内容样式 */
.note-content {
  line-height: 1.5;
  word-break: break-word;
}

.note-content :deep(br) {
  display: block;
  margin: 0.3em 0;
}

/* 图片预览样式（方形缩略图） */
.note-image {
  width: 120px;
  height: 120px;
  min-width: 120px;
  max-width: 120px;
  flex: 0 0 120px; /* 禁止在 flex 容器中随屏幕收缩 */
  border-radius: 8px;
  cursor: zoom-in;
  overflow: hidden;
}

/* 菜单按钮定位 */
.menu-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 1;
}
</style>

<i18n>
{
  "zhHans": {
    "edited": "已编辑"
  },
  "en": {
    "edited": "Edited"
  }
}
</i18n>
